﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SportsStore.Domain.Entities
{
    public class Cart
    {
        private readonly List<CartLine> _cartLines;

        public Cart()
        {
            _cartLines = new List<CartLine>();
        }

        public Cart AddItem(Product product, int quantity)
        {
            var cartLine = _cartLines.FirstOrDefault(x => x.Item == product);
            if (cartLine == null)
            {
                _cartLines.Add(new CartLine {Item = product, Quantity = quantity});
            }
            else
            {
                cartLine.Quantity += quantity;
            }

            return this;
        }

        public Cart DecreaseItem(Product product, int minus)
        {
            return DiffItem(product, -minus);
        }

        public Cart IncreaseItem(Product product, int incre)
        {
            return DiffItem(product, incre);
        }

        public Cart RemoveLine(Product product)
        {
            _cartLines.RemoveAll(x => x.Item == product);
            return this;
        }

        public decimal Bill()
        {
            return _cartLines.Sum(x => x.Item.Price*x.Quantity);
        }

        public void Clear()
        {
            _cartLines.Clear();
        }

        public IEnumerable<CartLine> Lines
        {
            get { return _cartLines; }
        }

        private Cart DiffItem(Product product, int diff)
        {
            var cartLine = _cartLines.FirstOrDefault(x => x.Item == product);
            if (cartLine == null)
            {
                throw new NullReferenceException("This product is not in cart");
            }

            cartLine.Quantity += diff;
            cartLine.Quantity = cartLine.Quantity < 0 ? 0 : cartLine.Quantity;

            return this;
        }
    }

    public class CartLine
    {
        public Product Item { get; set; }
        public int Quantity { get; internal set; }
    }
}
